package com.store.controller;

import com.store.entity.User;
import com.store.service.EmailService;
import com.store.service.UserService;
import com.store.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController

@Api("用户控制层")
@RequestMapping("/user")
public class UserController extends BaseController{

    @DubboReference(interfaceClass = UserService.class,version = "1.0.0",timeout = 5000)
    private UserService userService;

    @DubboReference(interfaceClass = EmailService.class,version = "1.0.0",timeout = 5000)
    private EmailService emailService;

    @ApiOperation("登录")
    @RequestMapping("/login")
    public JsonResult login(User user, HttpSession session){
        User exists = userService.getUserByUsername(user.getUsername(), user.getPassword());
        //数据存入session
        session.setAttribute("username",exists.getUsername());
        session.setAttribute("uid",exists.getUid());
        session.setAttribute("avatar",exists.getAvatar());
        return new JsonResult(200);
    }

    @ApiOperation("注册")
    @RequestMapping("/register")
    public JsonResult register(User user){
        userService.addUser(user);
        return new JsonResult(200);
    }

    @ApiOperation("发送验证码")
    @PostMapping("/send")
    public JsonResult send(HttpSession session){
        String username = (String)session.getAttribute("username");
        String checkNum = emailService.getCheckNum(username);
        String text = emailService.retrieveMess(username, checkNum);
        String email = userService.getEmail(username);
        emailService.sendEmail(email,"账号密码重置通知",text);
        //验证码存入session
        session.setAttribute("checkNum",checkNum);
        //验证码有效期90秒
        session.setMaxInactiveInterval(90);
        return new JsonResult(200);
    }

    @ApiOperation("重置密码")
    @PostMapping("/update")
    public JsonResult update(String newPassword,String checkNum,HttpSession session){
        String checkNum1 = (String) session.getAttribute("checkNum");
        String msg = "";
        Integer status = 200;
        if(!checkNum.equals(checkNum1)){
            status = 509;
            msg = "验证码错误";
        }else {
            Integer uid = (Integer)session.getAttribute("uid");
            userService.updateUserPassword(uid,newPassword);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(status);
        jsonResult.setMessage(msg);
        return jsonResult;
    }
}
